<template>
    <div class="menu-manage">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span>菜谱管理</span>
                    <el-button type="primary" @click="handleAdd">添加菜品</el-button>
                </div>
            </template>

            <!-- 搜索栏 -->
            <div class="search-bar">
                <el-input
                    v-model="searchForm.name"
                    placeholder="菜品名称"
                    style="width: 200px; margin-right: 10px"
                />
                <el-select
                    v-model="searchForm.category"
                    placeholder="菜品类别"
                    style="width: 150px; margin-right: 10px"
                    clearable
                >
                    <el-option label="主食" value="主食" />
                    <el-option label="荤菜" value="荤菜" />
                    <el-option label="素菜" value="素菜" />
                    <el-option label="汤类" value="汤类" />
                </el-select>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="resetSearch">重置</el-button>
            </div>

            <!-- 菜品列表 -->
            <el-table :data="menuList" style="width: 100%" v-loading="loading">
                <el-table-column prop="name" label="菜品名称" />
                <el-table-column prop="category" label="类别" width="100" />
                <el-table-column prop="price" label="价格" width="100">
                    <template #default="scope">
                        ¥{{ scope.row.price }}
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" show-overflow-tooltip />
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                            {{ scope.row.status === 1 ? '上架' : '下架' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="250" fixed="right">
                    <template #default="scope">
                        <el-button
                            size="small"
                            type="primary"
                            @click="handleEdit(scope.row)"
                        >编辑</el-button>
                        <el-button
                            size="small"
                            :type="scope.row.status === 1 ? 'warning' : 'success'"
                            @click="handleStatusChange(scope.row)"
                        >{{ scope.row.status === 1 ? '下架' : '上架' }}</el-button>
                        <el-button
                            size="small"
                            type="danger"
                            @click="handleDelete(scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </el-card>

        <!-- 添加/编辑对话框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="dialogType === 'add' ? '添加菜品' : '编辑菜品'"
            width="50%"
        >
            <el-form
                ref="menuFormRef"
                :model="menuForm"
                :rules="rules"
                label-width="100px"
            >
                <el-form-item label="菜品名称" prop="name">
                    <el-input v-model="menuForm.name" placeholder="请输入菜品名称" />
                </el-form-item>
                <el-form-item label="类别" prop="category">
                    <el-select v-model="menuForm.category" placeholder="请选择类别">
                        <el-option label="主食" value="主食" />
                        <el-option label="荤菜" value="荤菜" />
                        <el-option label="素菜" value="素菜" />
                        <el-option label="汤类" value="汤类" />
                    </el-select>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-input-number
                        v-model="menuForm.price"
                        :precision="2"
                        :step="0.1"
                        :min="0"
                    />
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input
                        type="textarea"
                        v-model="menuForm.description"
                        :rows="3"
                        placeholder="请输入菜品描述"
                    />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="menuForm.status">
                        <el-radio :label="1">上架</el-radio>
                        <el-radio :label="0">下架</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/utils/axios'

// 搜索表单
const searchForm = reactive({
    name: '',
    category: ''
})

// 表格数据
const menuList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add')
const menuFormRef = ref(null)

// 表单数据
const menuForm = reactive({
    id: null,
    name: '',
    category: '',
    price: 0,
    description: '',
    status: 1
})

// 表单验证规则
const rules = {
    name: [
        { required: true, message: '请输入菜品名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    category: [
        { required: true, message: '请选择类别', trigger: 'change' }
    ],
    price: [
        { required: true, message: '请输入价格', trigger: 'blur' }
    ],
    description: [
        { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
    ]
}

// 加载菜品列表
const loadMenuList = async () => {
    loading.value = true
    try {
        const response = await axios.get('/dining/menu/list', {
            params: {
                pageNum: currentPage.value,
                pageSize: pageSize.value,
                name: searchForm.name || undefined,
                category: searchForm.category || undefined
            }
        })
        if (response.data.code === 200) {
            menuList.value = response.data.result.records
            total.value = response.data.result.total
        }
    } catch (error) {
        console.error('获取菜品列表失败:', error)
        ElMessage.error('获取菜品列表失败')
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    loadMenuList()
}

// 重置搜索
const resetSearch = () => {
    searchForm.name = ''
    searchForm.category = ''
    currentPage.value = 1
    loadMenuList()
}

// 分页处理
const handleSizeChange = (val) => {
    pageSize.value = val
    loadMenuList()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    loadMenuList()
}

// 添加菜品
const handleAdd = () => {
    dialogType.value = 'add'
    menuForm.id = null
    menuForm.name = ''
    menuForm.category = ''
    menuForm.price = 0
    menuForm.description = ''
    menuForm.status = 1
    dialogVisible.value = true
}

// 编辑菜品
const handleEdit = (row) => {
    dialogType.value = 'edit'
    Object.assign(menuForm, row)
    dialogVisible.value = true
}

// 修改状态
const handleStatusChange = async (row) => {
    try {
        const newStatus = row.status === 1 ? 0 : 1
        await axios.put(`/dining/menu/${row.id}/status`, {
            status: newStatus
        })
        ElMessage.success('状态更新成功')
        row.status = newStatus
    } catch (error) {
        console.error('更新状态失败:', error)
        ElMessage.error('更新状态失败')
    }
}

// 删除菜品
const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除该菜品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await axios.delete(`/dining/menu/${row.id}`)
            ElMessage.success('删除成功')
            loadMenuList()
        } catch (error) {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    })
}

// 提交表单
const handleSubmit = async () => {
    if (!menuFormRef.value) return
    
    await menuFormRef.value.validate(async (valid) => {
        if (!valid) return
        
        try {
            if (dialogType.value === 'add') {
                await axios.post('/dining/menu', menuForm)
                ElMessage.success('添加成功')
            } else {
                await axios.put(`/dining/menu/${menuForm.id}`, menuForm)
                ElMessage.success('更新成功')
            }
            dialogVisible.value = false
            loadMenuList()
        } catch (error) {
            console.error('操作失败:', error)
            ElMessage.error('操作失败')
        }
    })
}

onMounted(() => {
    loadMenuList()
})
</script>

<style scoped>
.menu-manage {
    padding: 20px;
}

.search-bar {
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.el-tag {
    margin-right: 8px;
}
</style> 